package com.serkol.ams.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.serkol.ams.bean.LoginConfig;
import com.serkol.ams.bean.MyPage;
import com.serkol.ams.entity.LoginLog;
import com.serkol.ams.entity.Users;
import com.serkol.ams.entity.UsersAuthentication;
import com.serkol.ams.mapper.UsersMapper;
import com.serkol.ams.modal.SqlFeildModal;
import com.serkol.ams.service.LoginLogService;
import com.serkol.ams.service.UsersAuthenticationService;
import com.serkol.ams.service.UsersService;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultCode;
import com.serkol.exception.AuthException;
import com.serkol.handler.MyLambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author pingan
 * @description 针对表【users】的数据库操作Service实现
 * @createDate 2022-09-16 19:40:18
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
        implements UsersService {
    @Autowired
    private UsersAuthenticationService usersAuthenticationService;
    @Autowired
    private LoginLogService loginLogService;

    @Override
    public Users findByLogin(String openid) {

        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Users::getOpenid, openid);
        queryWrapper.last("LIMIT  1");
        return this.getOne(queryWrapper);
    }

    @Override
    public Users findByLoginAndInsert(Users usersDetail) {

        boolean b = this.saveOrUpdate(usersDetail);
        return usersDetail;
    }


    @Override
    public Users findByUserId(Long userId) {
        if (userId != null) {
            return this.getById(userId);
        } else {
            return null;
        }
    }

    @Override
    public Long findByUserCount(Long userId) {
        LambdaUpdateWrapper<Users> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();

        lambdaUpdateWrapper.eq(Users::getParentUserId, userId);
        return this.count(lambdaUpdateWrapper);
    }

    @Override
    public boolean editPhoneNumber(String phoneNumber) {
        LoginLog loginLog = AuthConstant.getLoginLog();
        LambdaUpdateWrapper<Users> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(Users::getPhone, phoneNumber);
        lambdaUpdateWrapper.eq(Users::getId, loginLog.getUserId());
        return this.update(lambdaUpdateWrapper);
    }
   // @Cacheable(cacheNames = "userstree::back", key = "'getParentUsersLevel'+#byUserId")
    @Override
    public Map<Integer, Users> getParentUsersLevel(Users byUserId) {
        Map<Integer, Users> map = new HashMap<>();
        map.put(1, byUserId);
        Users byUserId1 = findByUserId(byUserId.getParentUserId());
        if (byUserId1 != null) {
            map.put(2, byUserId1);
            Users byUserId2 = findByUserId(byUserId1.getParentUserId());
            if (byUserId2 != null) {
                map.put(3, byUserId2);
            }
        }
        return map;
    }
    @Cacheable(cacheNames = "userstree::back", key = "'getParentUsersLevelIds'+#parentId")
    @Override
    public List<Long> getParentUsersLevelIds(long parentId) {

        return getParentUsersLevelIdL(parentId, null);
    }

    private List<Long> getParentUsersLevelIdL(long parentId, List<Long> children) {
        if (children == null) {
            children = new ArrayList<>();
        }
        if (parentId > 0) {
            MyLambdaQueryWrapper<Users> queryWrapper1 = new MyLambdaQueryWrapper<>();
            queryWrapper1.eq(Users::getId, parentId);

            if (this.baseMapper.exists(queryWrapper1)) {
                System.out.println("PARENT——ID:" + parentId);
                Users next = this.getById(parentId);
                System.out.println("-----------------------------------------");
                System.out.println(next);
                System.out.println("-----------------------------------------");
                children.add(next.getId());
                if (next.getParentUserId() != null) {
                    children = getParentUsersLevelIdL(next.getParentUserId(), children);

                }
            }
        }
        return children;
    }
    @Cacheable(cacheNames = "userstree::back", key = "'getFindChildrens'+#parentId")
    @Override
    public List<Long> getFindChildrens(Long parentId) {

        return getFindChildrensL(parentId,true);
    }

    @Override
    public List<Long> getFindByMyUsers(long parentUserId) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("IFNULL(ID,0)");

        queryWrapper.lambda().eq(Users::getParentUserId, parentUserId);

//Long.parseLong(o.toString())
        List<Long> longs = this.listObjs(queryWrapper, (o) -> {
            System.out.println("NULLLLLL:" + o);

            return Long.parseLong(o + "");
        });
        return longs;
    }

    public List<Long> getFindChildrensL(Long parentId,boolean flag) {
        List<Long> children = new ArrayList<>();
        MyLambdaQueryWrapper<Users> queryWrapper = new MyLambdaQueryWrapper<>();
       if (parentId == null && flag) {
            queryWrapper.isNull(Users::getParentUserId).gt(Users::getAgentId, 1);
        } else {
            queryWrapper.eq(Users::getParentUserId, parentId);
        }
       // queryWrapper.eq(Users::getParentUserId, parentId);
        List<Users> list = this.list(queryWrapper);
        for (Users next : list) {
            children.add(next.getId());
            if (next.getId() != null && next.getId() > 0) {
                List<Long> findChildrensL = getFindChildrensL(next.getId(),false);
                children.addAll(findChildrensL);
            }
        }
        return children;
    }

    @Override
    public MyPage<Map<String, Object>> findByMiniList(int pageSize, int current, long agentId, long userId) {
        LoginLog loginLog = AuthConstant.getLoginLog();
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(Users::getCreateDate);
        queryWrapper.select(SqlFeildModal.getUsersAgentFeild());
        if (agentId > 0) {
            queryWrapper.lambda().eq(Users::getAgentId, agentId);
        }
        if (userId > 0) {
            queryWrapper.lambda().eq(Users::getParentUserId, userId);
        }else {
            queryWrapper.lambda().eq(Users::getParentUserId, loginLog.getUserId());
        }
        Page<Map<String, Object>> page = new Page<>(current, pageSize);
        IPage<Map<String, Object>> data = this.baseMapper.selectMapsPage(page, queryWrapper);


        return MyPage.parsePage(data);

    }

    @Cacheable(cacheNames = "userstree", key = "'findMyTreeList'+#parentUserId+'::pageSize'+#pageSize+'::current'+#current")
    @Override
    public MyPage<Map<String, Object>> findParentByMiniList(int pageSize, int current, long parentUserId) {


        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(Users::getCreateDate).eq(Users::getDeleted, 0);
        queryWrapper.select(SqlFeildModal.getUsersAgentFeild());

        queryWrapper.lambda().eq(Users::getParentUserId, parentUserId);

        Page<Map<String, Object>> page = new Page<>(current, pageSize);
        IPage<Map<String, Object>> data = this.baseMapper.selectMapsPage(page, queryWrapper);


        return MyPage.parsePage(data);
    }

    @Override
    public Users findByUserLogin(LoginConfig loginConfig) throws AuthException {

        Users login = this.baseMapper.login(loginConfig.getUserName(), loginConfig.getPassword());
        if (login != null) {
            return login;
        } else {
            throw new AuthException(ResultCode.OK_CONTENT_NO, "mini.memberdoesnotexist");
        }
    }

    @Override
    public MyPage<Map<String, Object>> findByList(int pageSize, int current, String invite, String userName, String nickname, String phone, String authName
            , long id
            , long agentId, int status) {

        MyLambdaQueryWrapper<Users> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(SqlFeildModal.getUsersFeild()).eq(Users::getDeleted, 0);

        if (StringUtils.isNotEmpty(invite)) {
            queryWrapper.likeRight(Users::getInvite, invite);
        }
        if (StringUtils.isNotEmpty(userName)) {
            queryWrapper.likeRight(Users::getUserName, userName);
        }
        if (StringUtils.isNotEmpty(nickname)) {
            queryWrapper.likeRight(Users::getNickname, nickname);
        }

        if (StringUtils.isNotEmpty(phone)) {
            queryWrapper.like(Users::getPhone, phone);
        }
        if (StringUtils.isNotEmpty(authName)) {
          //  queryWrapper.lambda().likeRight(Users::getAuthName, authName);
            queryWrapper.inSql(Users::getId, SqlFeildModal.getAuthNameLike(authName));
        }
        if (id > 0) {
            queryWrapper.eq(Users::getId, id);
        }
        if (agentId > 0) {
            queryWrapper.eq(Users::getAgentId, agentId);
        }

       if(status>-5) {
           queryWrapper.eq(Users::getStatus, status);
       }


        queryWrapper.orderByDesc(Users::getId);
        Page<Map<String, Object>> page = new Page<>(current, pageSize);
        Page<Map<String, Object>> mapPage = this.baseMapper.selectMapsPage(page, queryWrapper);
        return MyPage.parsePage(mapPage);
    }

    @Override
    public Map<String, Object> getCurrentUser() {
        LoginLog loginLog = AuthConstant.getLoginLog();
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(SqlFeildModal.getCurrentUser());
        queryWrapper.lambda().eq(Users::getId, loginLog.getUserId());
        return this.getMap(queryWrapper);
    }

    @Cacheable(cacheNames = "userstree::back", key = "'getFindTreeList'+#userId")
    @Override
    public List<Map<String, Object>> getBackFindTreeList(long userId) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();

        queryWrapper.select(SqlFeildModal.getTreeUser()).lambda().eq(Users::getDeleted, 0);
        if (userId > 0) {
            queryWrapper.lambda().eq(Users::getParentUserId, userId);
            //   queryWrapper.lambda().in(Users::getId, getFindIds(userId));

        }
        queryWrapper.orderByDesc("ID");
        List<Map<String, Object>> maps = this.listMaps(queryWrapper);

        return maps;
    }


    @Cacheable(cacheNames = "userstree", key = "'getFindTreeList'+#userId")
    @Override
    public Map<String, Object> getFindTreeList(long userId) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        if (userId > 0) {
            Map<String, Object> next = findById(userId);
            map1.put("name", next.get("name"));
            map1.put("title", next.get("agentName"));
            map1.put("icon", next.get("avatar"));
            map.put("id", next.get("id"));
            map.put("value", map1);
            // Long id = Long.valueOf((String) next.get("id"));
            List<Map<String, Object>> findTreeList = getFindTreeListL(userId);
            map.put("children", findTreeList);
        } else {
            map1.put("name", "公司");
            map1.put("title", "系统");
            map1.put("icon", "http://");
            map.put("id", "c1");
            map.put("value", map1);


            List<Map<String, Object>> findTreeList = getFindTreeListL(0);
            map.put("children", findTreeList);
        }
        return map;
    }

    public List<Map<String, Object>> getFindTreeListL(long userId) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        List<Map<String, Object>> mapList = new ArrayList<>();

        queryWrapper.select(SqlFeildModal.getTreeUser()).lambda().eq(Users::getDeleted, 0);
        if (userId > 0) {
            queryWrapper.lambda().eq(Users::getParentUserId, userId);
            //   queryWrapper.lambda().in(Users::getId, getFindIds(userId));
            List<Map<String, Object>> list = this.listMaps(queryWrapper);
            for (Map<String, Object> next : list) {
                Map<String, Object> map = new HashMap<>();
                Map<String, Object> map1 = new HashMap<>();
                map1.put("name", next.get("name"));
                map1.put("title", next.get("agentName"));
                map1.put("icon", next.get("avatar"));
                map.put("id", next.get("id"));
                map.put("parentUserId", userId);
                map.put("value", map1);
                if (next.containsKey("id")) {
                    System.out.println("UUUUUUUU");
                    System.out.println(next.get("id"));
                    long id = Long.parseLong(String.valueOf(next.getOrDefault("id", 0)));
                    List<Map<String, Object>> findTreeList = getFindTreeListL(id);
                    map.put("children", findTreeList);
                }
                mapList.add(map);
            }

        }


        return mapList;
    }

    private List<Object> getFindIds(long parentUserId) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("IFNULL(ID,0)");
        if (parentUserId > 0) {
            queryWrapper.lambda().eq(Users::getParentUserId, parentUserId);
        }
//Long.parseLong(o.toString())
        List<Object> longs = this.listObjs((o) -> {
            System.out.println("NULLLLLL:" + o);

            return o;
        });
        longs.add(parentUserId);
        for (Object next : longs) {
            System.out.println("NULLLLLL1:" + next);
            if (next != null) {
                List<Object> findIds = this.getFindIds(Long.parseLong(next.toString()));
                longs.addAll(findIds);
            }
        }
        return longs;
    }

    @Override
    public MyPage<Map<String, Object>> findByPageBackAgentList(int pageSize, int current, long agentId, String invite, String name, String parentName, String phone, String wechat) {
        MyLambdaQueryWrapper<Users> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(Users::getId, Users::getNickname, Users::getPhone, Users::getInvite, Users::getAgentId, Users::getAgentId, Users::getParentUserId,  Users::getCreateDate);
        queryWrapper.select("ID as id", "NICKNAME as nickname", "PHONE as phone", "INVITE as invite","AVATAR as avatar",
                "AGENT_ID as agentId", "PARENT_USER_ID as parentUserId", "CREATE_DATE as createDate",
                "(SELECT NAME FROM users_authentication as tusers_authentication WHERE USER_ID=x.PARENT_USER_ID LIMIT 1) AS parentName",
                "(SELECT NAME FROM users_authentication as tusers_authentication WHERE tusers_authentication.USER_ID = x.id LIMIT 1) as name,(SELECT NAME FROM agent as tagent WHERE ID=x.AGENT_ID LIMIT 1) AS agentName");
 //       queryWrapper.tableAs(Users.class,"x");
   //  queryWrapper.select(SqlFeildModal.getUsersAgentFullFeild());

       /* sb.append("(SELECT NAME FROM users_authentication as tusers_authentication WHERE USER_ID=x.ID LIMIT 1) AS name,");
        sb.append("(SELECT COUNT(*) FROM users as tusers  WHERE PARENT_USER_ID=x.ID LIMIT 1) AS agentCount,");
        sb.append("(SELECT WECHAT FROM users_authentication as tusers_authentication WHERE USER_ID=x.ID LIMIT 1) AS wechat,");
        sb.append("(SELECT NAME FROM users_authentication as tusers_authentication WHERE USER_ID=x.PARENT_USER_ID LIMIT 1) AS parentName,");
        sb.append("(SELECT NAME FROM agent as tagent WHERE ID=x.AGENT_ID LIMIT 1) AS agentName");*/
    //  queryWrapper.authName(Users::getId).as("name");
      //  queryWrapper
                //.select("(SELECT COUNT(*) FROM users as tusers  WHERE PARENT_USER_ID=x.ID LIMIT 1)").as("agentCount")
           //    .select("(SELECT WECHAT FROM users_authentication as tusers_authentication WHERE USER_ID=x.ID LIMIT 1)").as("wechat")
            //   .select("(SELECT NAME FROM users_authentication as tusers_authentication WHERE USER_ID=x.PARENT_USER_ID LIMIT 1)").as("parentName")
           //     .select("(SELECT NAME FROM agent as tagent WHERE ID=x.AGENT_ID LIMIT 1)").as("agentName");

        if (agentId > 0) {
            queryWrapper.eq(Users::getAgentId, agentId);
        }
        if (StringUtils.isNotEmpty(invite)) {
            queryWrapper.likeRight(Users::getInvite, invite);
        }
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.inSql(Users::getId, SqlFeildModal.getAuthNameLike(name));
        }
        if (StringUtils.isNotEmpty(parentName)) {
            queryWrapper.inSql(Users::getParentUserId, SqlFeildModal.getAuthNameLike(parentName));
        }
        if (StringUtils.isNotEmpty(phone)) {
            queryWrapper.like(Users::getPhone, phone);
        }
        if (StringUtils.isNotEmpty(wechat)) {
            queryWrapper.inSql(Users::getId, SqlFeildModal.getAuthWechatLike(wechat));
        }
        queryWrapper.orderByDesc(Users::getId);
        Page<Map<String, Object>> page = new Page<>(current, pageSize);
        Page<Map<String, Object>> mapPage =this.pageMaps(page, queryWrapper);
        return MyPage.parsePage(mapPage);
    }

    @Override
    public Map<String, Object> findById(long id) {

        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(SqlFeildModal.getUsersFullFeild());
        queryWrapper.lambda().eq(Users::getId, id);
        Map<String, Object> map = this.getMap(queryWrapper);
        return map;
    }

    @Override
    public boolean isPhoneValid(String phone) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Users::getPhone, phone);
        boolean exists = this.baseMapper.exists(queryWrapper);
        System.out.println("----------------------------------------------------");
        System.out.println(exists);
        return exists;
    }

    @Override
    public Users findByUserPhone(String phone) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Users::getPhone, phone);
        queryWrapper.last("LIMIT 1");
        Users one = this.getOne(queryWrapper);
        return one;
    }

    @Override
    public boolean isPhoneAndIdValid(String phone, Long id) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Users::getPhone, phone).eq(Users::getId, id);
        boolean exists = this.baseMapper.exists(queryWrapper);
        return exists;
    }

    @Override
    public boolean isUsers(Long parentUserId) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Users::getId, parentUserId);
        boolean exists = this.baseMapper.exists(queryWrapper);
        return exists;
    }

    @Override
    public Map<String, Object> findByUserAuthPhone(String phone) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(SqlFeildModal.getUsersFullFeild());
        queryWrapper.lambda().eq(Users::getPhone, phone).last("LIMIT 1");
        Map<String, Object> map = this.getMap(queryWrapper);
        return map;
    }

    @Override
    public Map<String, Object> getUserStastic() {
        Map<String, Object> map = new HashMap<>();
        long count = this.count();
        map.put("users", count);
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.gt(Users::getAgentId, 1).eq(Users::getDeleted, 0);
        long count1 = this.count(queryWrapper);
        map.put("agent", count1);

        return map;
    }

    @Override
    public boolean changeAvatar(Long userId, Long id, String url) {

        LambdaUpdateWrapper<Users> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(Users::getAvatar, url);
        lambdaUpdateWrapper.eq(Users::getId, userId);
        boolean update = this.update(lambdaUpdateWrapper);
        return update;
    }

    @Override
    public Map<String, Object> findBySuorceId(Long userId) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(SqlFeildModal.getUsersFullSourceFeild());
        queryWrapper.lambda().eq(Users::getId, userId);
        Map<String, Object> map = this.getMap(queryWrapper);
        return map;
    }


    private List<Map<String, Object>> getFindByIds(List<Map<String, Object>> list, long parentUserId) {
        if (list == null) {
            list = new ArrayList<>();
        }
        MyLambdaQueryWrapper<Users> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(Users::getId).authName(Users::getId).as("name").select(Users::getParentUserId).as("parentUserId");
        queryWrapper.eq(Users::getId, parentUserId);
        queryWrapper.last("LIMIT 1");
        MyLambdaQueryWrapper<Users> queryWrapper1 = new MyLambdaQueryWrapper<>();
        queryWrapper1.eq(Users::getId, parentUserId);
        Map<String, Object> map = this.getMap(queryWrapper);
        if (map!=null) {

            list.add(map);
            if (map.containsKey("parentUserId")) {
                Object parentUserId1 = map.get("parentUserId");
                long l = Long.parseLong(String.valueOf(parentUserId1));
                if (l > 0) {
                    list = getFindByIds(list, l);
                    // list.addAll()
                }
            }

        }
        return list;
    }

    @Override
    public List<Map<String, Object>> findMyParentList(long userId) {
        List<Map<String, Object>> list = new ArrayList<>();
        Users byId = getById(userId);
        return getFindByIds(list, byId.getParentUserId());
    }

    @Override
    public List<Map<String, Object>> findMiniByUserAuthPhone(String phone) {
        MyLambdaQueryWrapper<Users> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(Users::getId).as("value")
                .select(Users::getId).as("id")
                .select(Users::getPhone).as("label").authName(Users::getId).as("name");
        queryWrapper.like(Users::getPhone, phone.trim());
        List<Map<String, Object>> maps = this.listMaps(queryWrapper);
        return maps;
    }

    @Override
    public Users findByLoginOrPhone(String openid, String phone) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Users::getPhone, phone).or().eq(Users::getOpenid, openid).eq(Users::getAgentId, 1);
        queryWrapper.last("LIMIT  1");
        return this.getOne(queryWrapper);

    }

    @Override
    public Users findByParentAgentUserId(Long parentId, long agentLevel) {
        return findByParentAgentUserIdL(parentId, agentLevel);
    }
    @Override
    public Users findByParentAgentUserIdLP(Long parentId, long agentLevel){
       return findByParentAgentUserIdLPL(parentId, agentLevel);
    }

    @Override
    public boolean byUsersDeleteOpenId(String openid) {
        LambdaUpdateWrapper<Users> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(Users::getOpenid, null).set(Users::getMpOpenid, null).set(Users::getMpSubscribe, 0).eq(Users::getOpenid, openid);
        return this.update(lambdaUpdateWrapper);
    }

    @Override
    public List<Users> findMyUserParentList(long userId) {
        List<Users> list = new ArrayList<>();
        Users byId = getById(userId);
        return getFindMyUserParentList(list, byId.getParentUserId());
    }

    @Override
    public Users findByUserIdAndPassword(Long userId, String password) {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getId, userId);
        queryWrapper.apply("USER_PASSWORD = MD5('"+password+"')");
        queryWrapper.last("LIMIT  1");
        return this.getOne(queryWrapper);
    }

    @Override
    public List<Map<String, Object>> findMyBrithList() {
        MyLambdaQueryWrapper<UsersAuthentication> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper
                .select(UsersAuthentication::getId).langName(UsersAuthentication::getName,UsersAuthentication::getNameUg).as("name")
                .select("CONCAT(SUBSTRING(IDCARD, 7, 4), '-', SUBSTRING(IDCARD, 11, 2), '-', SUBSTRING(IDCARD, 13, 2))").as("birthday").
                select("(SELECT AVATAR FROM users as tuser WHERE tuser.ID = x.USER_ID LIMIT 1)").as("avatar");
        queryWrapper.apply("DATE_FORMAT(NOW(), '%m%d') = CONCAT(SUBSTRING(IDCARD, 11, 2), SUBSTRING(IDCARD, 13, 2))");
        return usersAuthenticationService.listMaps(queryWrapper);
    }

    @Override
    public List<Users> findByAdminList() {
        MyLambdaQueryWrapper<Users> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(Users::getIsAdmin, 1).isNotNull(Users::getMpOpenid);
        try {
            return this.list(queryWrapper);
        } catch (Exception e) {
            log.error("findByAdminList error", e);
        }
        return List.of();
    }

    @Override
    public Users findByMpOpenId(String openid) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Users::getMpOpenid, openid);
        queryWrapper.last("LIMIT 1");
        Users one = this.getOne(queryWrapper);
        return one;

    }

    @Override
    public void unsubscribe(String openId) {
        Users byMpOpenId = findByMpOpenId(openId);
        if(byMpOpenId!=null) {
            byMpOpenId.setMpSubscribe(0);
            int i = this.baseMapper.updateById(byMpOpenId);
            if (i > 0) {
                loginLogService.outLogin(byMpOpenId.getId());
            }
        }
    }
    @Override
    public void subscribe(String openId) {
        Users byMpOpenId = findByMpOpenId(openId);
        if(byMpOpenId!=null) {
            byMpOpenId.setMpSubscribe(1);
            int i = this.baseMapper.updateById(byMpOpenId);

        }
    }

    private List<Users> getFindMyUserParentList(List<Users> list, long parentUserId) {
        if (list == null) {
            list = new ArrayList<>();
        }
        MyLambdaQueryWrapper<Users> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(Users::getId).authName(Users::getId).as("name").select(Users::getParentUserId).as("parentUserId");
        queryWrapper.eq(Users::getId, parentUserId);
        queryWrapper.last("LIMIT 1");
        MyLambdaQueryWrapper<Users> queryWrapper1 = new MyLambdaQueryWrapper<>();
        queryWrapper1.eq(Users::getId, parentUserId);
        Users map = this.getOne(queryWrapper);
        if (map!=null) {

            list.add(map);
            if (map.getParentUserId()!=null) {
                Object parentUserId1 = map.getParentUserId();
                long l = Long.parseLong(String.valueOf(parentUserId1));
                if (l > 0) {
                    list = getFindMyUserParentList(list, l);
                    // list.addAll()
                }
            }

        }
        return list;
    }


    public Users findByParentAgentUserIdL(Long parentId, long agentLevel) {
        MyLambdaQueryWrapper<Users> queryWrapper = new MyLambdaQueryWrapper<>();

        if (parentId != null) {
            queryWrapper.eq(Users::getId, parentId);

            Users one = this.getOne(queryWrapper);
            if (agentLevel == one.getAgentId()) {
                return one;
            } else {
                if(one.getParentUserId()!=null) {
                    Users findIds = this.findByParentAgentUserIdL(one.getParentUserId(), agentLevel);
                    if (agentLevel == findIds.getAgentId()) {
                        return findIds;
                    } else {
                        return null;
                    }
                }else {
                    return null;
                }
            }

        } else {
            return null;
        }
    }

    long lastId=0;
    public Users findByParentAgentUserIdLPL(Long parentId, long agentLevel) {
        System.out.println("parentId:"+parentId);
        System.out.println("agentLevel:"+agentLevel);
        MyLambdaQueryWrapper<Users> queryWrapper = new MyLambdaQueryWrapper<>();

        if (parentId != null) {
            queryWrapper.eq(Users::getId, parentId);

            Users one = this.getOne(queryWrapper);

            if (one.getAgentId()>agentLevel ||  one.getParentUserId()==null && one.getAgentId()==agentLevel) {
                System.out.println("parentId:10:"+parentId);
                System.out.println("agentLevel10:"+agentLevel);
                return one;
            } else {
                lastId=parentId;
                if(one.getParentUserId()!=null) {
                    System.out.println("parentId:1:"+parentId);
                    System.out.println("agentLevel1:"+agentLevel);
                    Users findIds = this.findByParentAgentUserIdLPL(one.getParentUserId(), agentLevel);
                    if ( findIds.getAgentId()>agentLevel) {
                        Users byId = this.getById(parentId);
                        System.out.println("-----------------parentId:2--:"+parentId);
                        System.out.println(byId);
                        return byId;
                    } else {

                        return findIds;
                    }
                }else {
                    return null;
                }
            }

        } else {
            return null;
        }
    }


}




